<template>
  <div class="body">
    <template v-if="$utils.checkLogin() && goodsList.length > 0">
      <div class="cart-top-tips">
        <div class="fz-small">
          共计 <span>{{ goodsList.length }}</span> 件
        </div>
        <hover>
          <div
            v-if="action === 'complete'"
            @click="switchAction('edit')"
            class="defalut"
          >
            编辑
          </div>
          <div
            v-if="action === 'edit'"
            @click="switchAction('complete')"
            class="defalut"
          >
            完成
          </div>
        </hover>
      </div>

      <!-- 商品列表 -->
      <div
        class="cart-main fade-show"
        v-if="goodsList.length > 0"
        :class="'cart-padding-layout'"
      >
        <div class="item" v-for="(item, index) in goodsList" :key="index">
          <!-- 选择框 -->
          <div
            class="item-radio"
            @click="onChecked(index)"
            v-if="item.goods_status.value || item.goods_stock > 0"
          >
            <checkbox :checked="item.checked" class="checkbox"></checkbox>
          </div>
          <div class="item-radio" v-else>
            <checkbox class="checkbox" :disabled="true"></checkbox>
          </div>
          <div class="goods-image">
            <image
              @click="toGoodsDetail(item.id)"
              class="image"
              :src="
                item.goods_sku.goods_img != ''
                  ? item.goods_sku.goods_img
                  : item.goods_image
              "
              mode="aspectFill"
            />
            <div class="goods-sell-out" v-if="item.goods_status.value == 20">
              <div class="goods-sell-out-text">已下架</div>
            </div>
            <div class="goods-sell-out" v-else-if="item.goods_stock == 0">
              <div class="goods-sell-out-text">已售罄</div>
            </div>
          </div>

          <div class="goods-info">
            <div class="goods-name" @click="toGoodsDetail(item.id)">
              {{ item.goods_name }}
            </div>
            <div class="mt4 fz-small-x text-grey">
              {{ item.goods_sku.sku_attr_text }}
            </div>

            <div class="flex mt4">
              <div class="goods-buy-limit" v-if="item.buy_limit_status">
                <div>限购</div>
                <div class="ml2">{{ item.buy_limit }}件</div>
              </div>
              <div class="goods-buy-least" v-if="item.buy_least_status">
                <div>起购</div>
                <div class="ml2">{{ item.buy_least }}件</div>
              </div>
            </div>

            <div class="goods-bottom-box">
              <div class="flex items-center">
                <money :value="item.goods_sku.price"></money>
                <money
                  class="ml5"
                  market
                  :value="item.goods_sku.market_price"
                ></money>
              </div>
              <div class="goods-num">
                <numberBox
                  v-model="item.total_num"
                  height="30"
                  width="60"
                  @change="changeNum"
                  :index="index"
                  :params="{
                    id: item.id,
                    skuid: item.goods_sku_id,
                  }"
                  :max="
                    item.buy_limit_status &&
                    item.goods_sku.stock > item.buy_limit &&
                    item.buy_limit > 0
                      ? item.buy_limit
                      : item.goods_sku.stock
                  "
                  :min="1"
                ></numberBox>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部结算信息 -->
      <div class="cart-bottom-box" :class="'taber-fixed-layout'">
        <div class="cart-bottom-left">
          <view class="checked-all">
            <checkbox
              :checked="checkedAll"
              @click="onCheckedAll"
              class="checkbox"
              :color="DIYTHEME?.host_bg"
            ></checkbox>
          </view>
          <div class="order-total flex">
            <div class="ml5 fz-small-x">合计:</div>
            <money fw :value="cartTotalPrice"></money>
            <!-- 运费信息 -->
            <template v-if="express.is_express">
              <div class="order-express text-grey ml5">
                <!-- 包邮 -->
                <!-- <div v-if="express.is_free">包邮</div>
              <div v-else class="flex items-center fz-small-xx">
                <div>快递费:</div>
                <div>￥{{ express.price }}</div>
              </div>
               -->
                <div class="fz-small-xx">不含运费</div>
              </div>
            </template>
          </div>
        </div>
        <div class="cart-bottom-btn">
          <hover>
            <div
              v-if="action === 'complete'"
              class="buy-btn"
              @click="toBuy"
              :style="[
                `background:linear-gradient(to right,${DIYTHEME?.host_bg2},${DIYTHEME?.host_bg});`,
                `color:${DIYTHEME?.host_color};`,
              ]"
            >
              去结算
            </div>
            <div v-if="action === 'edit'" @click="onDelete" class="default-btn">
              删除
            </div>
          </hover>
        </div>
      </div>
    </template>

    <empty
      img="4"
      text="购物车空荡荡"
      v-if="!$utils.checkLogin() || goodsList.length == 0"
    />
    <template v-if="$utils.checkLogin() && goodsList.length == 0">
      <div class="flex center items-center">
        <hover>
          <div
            class="gobtn"
            :style="[
              `background: ${DIYTHEME?.host_bg}`,
              `color: ${DIYTHEME?.host_color}`,
            ]"
            @click="$utils.routeRedirectTo('/pages/index/index')"
          >
            去逛逛
          </div>
        </hover>
      </div>
    </template>
    <template v-if="!$utils.checkLogin()">
      <div class="flex center items-center">
        <hover>
          <div
            class="gobtn"
            :style="[
              `background: ${DIYTHEME?.host_bg}`,
              `color:${DIYTHEME?.host_color}`,
            ]"
            @click="toLogin"
          >
            去登录
          </div>
        </hover>
      </div>
    </template>
    <init-load ref="initLoadRef" v-if="initLoading"></init-load>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, nextTick } from "vue";
import numberBox from "@/components/ui/numberbox/index.vue";
import { Result, ResultError, expressDataType } from "@/types";
import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
import { useConfig } from "@/store";
import { getCartList } from "@/api/cart";
import { storeToRefs } from "pinia";
import { updateCart, deleteCart } from "@/api/cart";

const { DIYTHEME } = storeToRefs(useConfig());
const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

// 当前动作
const action = ref<string>("complete");

const goodsList = ref<Array<any>>([]);

// 是否全选
const checkedAll = ref<boolean>(false);

/**
 * 切换编辑/完成
 */
const switchAction = (t: string) => {
  action.value = t;
};

const initLoading = ref<boolean>(false);

const express = ref<expressDataType>({
  is_express: 0,
  price: "0.00",
  is_free: 0,
});

// 订单金额
const cartTotalPrice = ref<string | number>(0.0);

const toInit = () => {
  initLoading.value = true;
  getCartList()
    .then((res: Result) => {
      // goodsList.value = res.data.goods_list;
      express.value = res.data.express;
      initGoodsChecked(res.data);
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      initLoading.value = false;
      $utils.errorMsg(err);
    });
};

const initGoodsChecked = (data: any) => {
  let checkedData = getCheckedData();
  // 将商品设置选中
  if (!data.goods_list) {
    goodsList.value = [];
    cartTotalPrice.value = "0.00";
    checkedAll.value = false;
    return false;
  }
  if (data.goods_list) {
    data.goods_list.forEach((item: any) => {
      item.checked = $utils.inArray(
        `${item.id}_${item.goods_sku_id}`,
        checkedData
      );
    });
  }
  goodsList.value = data.goods_list;
  cartTotalPrice.value = data.order_pay_price;
  checkedAll.value = checkedData.length == data.goods_list.length;
  // 更新购物车已选商品总价格
  updateTotalPrice();
};

onShow(() => {
  if ($utils.checkLogin()) {
    toInit();
  }
});

onPullDownRefresh(() => {
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 300);
  setTimeout(() => {
    toInit();
  }, 500);
});

/**
 * 选择框选中
 */
const onChecked = (index: number) => {
  let goods = goodsList.value[index],
    checked = !goods.checked;
  // 选中状态
  goodsList.value[index].checked = checked;
  // 更新选中记录
  onUpdateChecked();
  // 更新购物车已选商品总价格
  updateTotalPrice();
  if (!goodsList.value) {
    return false;
  }
  // 更新全选状态
  checkedAll.value = getCheckedData().length == goodsList.value.length;
};

/**
 * 更新商品选中记录
 */
const onUpdateChecked = () => {
  let checkedData: any = [];
  goodsList.value.forEach((item) => {
    if (item.checked == true) {
      checkedData.push(`${item.id}_${item.goods_sku_id}`);
    }
  });
  $utils.setStorage("checkedData", checkedData);
};

/**
 * 获取选中的商品
 */
const getCheckedData = () => {
  let checkedData = $utils.getStorage("checkedData");
  return checkedData ? checkedData : [];
};

/**
 * 选择框全选
 */
const onCheckedAll = () => {
  if (!goodsList.value) {
    return false;
  }
  // 更新商品选中记录
  goodsList.value.forEach((item: any) => {
    item.checked = !checkedAll.value;
  });
  checkedAll.value = !checkedAll.value;
  // 更新购物车已选商品总价格
  updateTotalPrice();
  // 更新选中记录
  onUpdateChecked();
};

/**
 * 更新购物车已选商品总价格
 */
const updateTotalPrice = () => {
  let totalPrice = 0;
  goodsList.value.forEach((item) => {
    if (item.checked === true) {
      totalPrice = $utils.mathadd(totalPrice, item.total_price);
    }
  });
  cartTotalPrice.value = Number(totalPrice).toFixed(2);
};
/**
 * 获取已选中的商品
 */
const getCheckedIds = () => {
  let arrIds: any = [];
  goodsList.value.forEach((item) => {
    if (item.checked === true) {
      arrIds.push(`${item.id}_${item.goods_sku_id}`);
    }
  });
  return arrIds;
};

const changeNum = (obj: {
  value: string | number;
  index: number;
  params: any;
}) => {
  // goodsList.value[obj.index].total_num = obj.value;

  updateCart({
    goods_id: obj.params.id,
    goods_num: obj.value,
    goods_sku_id: obj.params.skuid,
  })
    .then((res: Result) => {
      toInit();
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

/**
 * 商品删除事件
 */
const onDeleteEvent = (cartIds: string[]) => {
  cartIds.forEach((cartId: string) => {
    goodsList.value.forEach((item, goodsIndex: number) => {
      if (cartId == `${item.id}_${item.goods_sku_id}`) {
        goodsList.value.splice(goodsIndex, 1);
      }
    });
  });
  // 更新选中记录
  onUpdateChecked();
  return true;
};

const onDelete = () => {
  let cartIds = getCheckedIds();
  if (!cartIds.length) {
    uni.showToast({
      title: "您还没有选择商品",
      icon: "none",
    });
    return false;
  }
  uni.showModal({
    title: "提示",
    content: "您确定要移除选择的商品吗?",
    success(e) {
      e.confirm && toDelete();
    },
  });
};
const toDelete = () => {
  let cartIds = getCheckedIds();
  deleteCart({
    cart_id: cartIds.toString(),
  })
    .then((res: Result) => {
      // 删除选中的商品
      onDeleteEvent(cartIds);
      // 获取购物车列表
      toInit();
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const toLogin = () => {
  $utils.routeRedirectTo("/pages/login/index");
  // proxy?.$refs["loginRef"]?.open();
};

const toGoodsDetail = (goodsId: number) => {
  $utils.routeRedirectTo("/pages/goods/detail", { id: goodsId });
};

// 立即购买
const toBuy = () => {
  let cartIds = getCheckedIds();
  if (!cartIds.length) {
    $utils.errorMsg("您还没有选择商品");
    return false;
  }
  $utils.routeRedirectTo("/otherpages/order/buy/index", {
    ids: cartIds,
  });
};
</script>

<style>
page {
  background: var(--base-page);
}
</style>
<style scoped>
.cart-top-tips {
  height: 60rpx;
  line-height: 60rpx;
  background: var(--base-page);
  position: fixed;
  top: 0;
  width: calc(100% - 40rpx);
  left: 0;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 9;
}

.cart-main {
  width: calc(100% - 40rpx);
  margin: 60rpx 20rpx 120rpx;
}
.cart-main .item {
  width: calc(100% - 40rpx);
  height: 160rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  border-radius: var(--base-radius-default);
  margin-bottom: 20rpx;
}
.cart-main .item .goods-image {
  height: 160rpx;
  position: relative;
  width: 160rpx;
}
.cart-main .item .goods-image .image {
  height: 160rpx;
  width: 160rpx;
  border-radius: var(--base-radius-small);
}
.cart-main .item .item-radio {
  align-items: center;
  height: 160rpx;
  display: inherit;
  width: 40rpx;
}

.goods-info {
  width: calc(100% - 230rpx);
  position: relative;
}
.goods-name {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.goods-num {
  display: inherit;
  align-items: center;
}
.goods-bottom-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
}
.goods-bottom-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
}

.gobtn {
  margin: 0 auto;
  padding: 15rpx 60rpx;
  border-radius: 50rpx;
}

.cart-bottom-box {
  width: calc(100% - 40rpx);
  height: 80rpx;
  padding: 10rpx 20rpx;
  background: #fff;
  position: fixed;
  align-items: center;
  display: flex;
  justify-content: space-between;
  white-space: nowrap;
  left: 0;
  bottom: 0;
  border-top: 1rpx solid #f5f5f5;
  z-index: 9;
}
.cart-bottom-left {
  display: flex;
  justify-content: flex-start;
  font-size: var(--base-size-default);
  line-height: 60rpx;
}

.default-btn {
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  border-radius: var(--base-radius-small);
  background: #f0f0f0;
}

.buy-btn {
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: var(--base-radius-small);
  font-size: var(--base-size-small);
  background: #f0f0f0;
}
.cart-padding-layout {
  padding-bottom: 100rpx;
}
</style>